/**
 * author: vformAdmin
 * email: vdpadmin@163.com
 * website: https://www.vform666.com
 * date: 2021.08.18
 * remark: 如果要分发VForm源码，需在本文件顶部保留此文件头信息！！
 */

import { copyWidgetList, deepClone, generateId } from '@/utils/util'
import { widgetList } from '@/designer/widget-panel/widgetsConfig.js'
import eventBus from '@/utils/event-bus'
import * as CONST from './const'

/**
 * 根据name初始化页面
 * @param {string} name 页面的名称
 * @returns 初始页面
 */
const initPage = (name, page = { options: {} }) => {
  console.log('initPage', name, page)
  return {
    // 页面的ID
    id: page.id || CONST.DESIGNER_TYPE.UI + generateId(),
    // 类型: Page代表页面
    type: page.type || CONST.DESIGNER_TYPE.UI,
    // 页面内组件的序号
    lastId: page.lastId || 0,
    // Lua页面内用户触发事件的Id
    lastUserId: page.lastUserId || 20000,
    // 页面的属性
    options: {
      id: page.options.id || 0,
      name: page.options.name || name,
      bgType: page.options.bgType || CONST.PAGE_DEFAULT_PROPS.BG_TYPE,
      img: page.options.img || CONST.PAGE_DEFAULT_PROPS.IMG,
      rgb: page.options.rgb || CONST.PAGE_DEFAULT_PROPS.RGB,
      opa: page.options.opa || CONST.PAGE_DEFAULT_PROPS.OPA,
      code:
        page.options.code ||
        'function on_systick_ui()--定时器 \r\nend \r\n\r\nfunction on_control_notify(objId, type, user_data, value)--回调函数 \r\nend\r\n'
      // code: page.options.code || ''
    },
    // 页面组件列表
    widgetList: page.widgetList || []
  }
}

/**
 * 根据页面的名称，页面的数据生成一个designer示例
 */
export function createDesigner(vueInstance, size, name, page) {
  page = initPage(name, page)

  return {
    vueInstance,
    size,
    ...page,
    options: {
      ...page.options
    },

    editedWidget: null, // 正在编辑的组件
    selectedWidget: null, // 当前选中组件
    copyWidget: null, //复制组件
    showWidgetId: false, //是否显示组件id
    showWidgetData: false, //是否显示组件绑定数据

    dragWidget: null, //拖拽组件

    formWidget: null, //表单设计容器

    cssClassList: [], //自定义样式列表

    historyData: {
      index: -1, //index: 0,
      maxStep: 20,
      steps: []
    },
    // 添加设置显示数据的方法
    setShowWidgetData(flag) {
      this.showWidgetData = flag
    },

    clearDesigner(skipHistoryChange) {
      let emptyWidgetListFlag = this.widgetList.length === 0
      this.widgetList = []
      this.selectedWidget = null

      if (skipHistoryChange) {
        //什么也不做！！
      } else if (!emptyWidgetListFlag) {
        this.emitHistoryChange()
      } else {
        this.saveCurrentHistoryStep()
      }
    },

    setSelected(selected) {
      try {
        if (!selected) {
          // 使用 nextTick 确保 DOM 更新完成
          this.vueInstance?.$nextTick?.().then(() => {
            if (this.vueInstance?.$refs?.settingRef) {
              this.vueInstance.$refs.settingRef.setCurrentKey(this.id)
            }
          })
          this.selectedWidget = null
          return
        }

        this.selectedWidget = selected

        // 使用 $nextTick 确保 DOM 更新完成后再访问 settingRef
        this.vueInstance?.$nextTick?.().then(() => {
          if (this.vueInstance?.$refs?.settingRef) {
            try {
              this.vueInstance.$refs.settingRef.setCurrentKey(selected.id)
            } catch (e) {
              console.error('Error setting current key:', e)
            }
          } else {
            console.warn('settingRef not available, retrying...')
            // 可选：添加重试逻辑或延迟处理
          }
        })
      } catch (error) {
        console.error('Error in setSelected:', error)
        // 添加错误恢复逻辑
        this.selectedWidget = selected // 至少确保选中状态更新
      }
    },

    checkWidgetMove(evt) {
      /* Only field widget can be dragged into sub-form */
      if (evt.draggedContext && evt.draggedContext.element) {
        let wgCategory = evt.draggedContext.element.category
        if (evt.to) {
          if (evt.to.className === 'sub-form-table' && wgCategory === 'container') {
            //this.$message.info(this.vueInstance.i18nt('designer.hint.onlyFieldWidgetAcceptable'))
            return false
          }
        }
      }

      return true
    },

    checkFieldMove(evt) {
      if (!!evt.draggedContext && !!evt.draggedContext.element) {
        let wgType = evt.draggedContext.element.type + ''
        if (evt.to) {
          if (evt.to.className === 'sub-form-table' && wgType === 'slot') {
            //this.$message.info(this.vueInstance.i18nt('designer.hint.onlyFieldWidgetAcceptable'))
            return false
          }
        }
      }

      return true
    },

    getContainerByType(typeName) {
      let allWidgets = [...widgetList]
      let foundCon = null
      allWidgets.forEach((con) => {
        if (!!con.type && con.type === typeName) {
          foundCon = con
        }
      })

      return foundCon
    },

    getFieldWidgetByType(typeName) {
      let allWidgets = [...widgetList]
      let foundWidget = null
      allWidgets.forEach((widget) => {
        if (!!widget.type && widget.type === typeName) {
          foundWidget = widget
        }
      })

      return foundWidget
    },

    hasConfig(widget, configName) {
      let originalWidget = null
      originalWidget = this.getFieldWidgetByType(widget.type)

      if (!originalWidget || !originalWidget.options) {
        return false
      }

      return Object.keys(originalWidget.options).indexOf(configName) > -1
    },

    // 设置当前拖动的组件
    drag(widget) {
      this.dragWidget = widget
    },

    addDragWidget(widget, parent) {
      if (parent) {
        parent.widgetList.push(widget)
        return
      }
      this.widgetList.push(widget)
    },

    copyNewFieldWidget(origin, parent) {
      let newWidget = deepClone(origin)
      let tempId = generateId()
      newWidget.id = newWidget.type.replace(/-/g, '') + tempId

      let lastId = this.getLastId()
      newWidget.options.id = lastId
      newWidget.options.name = `${newWidget.type}${lastId}`
      if (newWidget.options.userId) {
        newWidget.options.userId = this.getLastUserId()
      }
      if (parent) {
        newWidget.options.parentId = parent.id
        newWidget.options.baseId = parent.options.id
      }

      delete newWidget.displayName
      return newWidget
    },

    // 在 designer.js 中修改 copySelectedWidget 方法
    copySelectedWidget(copyWidget) {
      let newWidget = deepClone(copyWidget)
      let tempId = generateId()
      newWidget.id = newWidget.type.replace(/-/g, '') + tempId

      let lastId = this.getLastId()
      newWidget.options.id = lastId
      newWidget.options.name = `${newWidget.type}${lastId}`

      if (newWidget.options.userId) {
        newWidget.options.userId = this.getLastUserId()
      }

      // 如果是模块组件，需要特殊处理其内部的 widgetList
      if (newWidget.widgetList) {
        this.copyWidgetListForModule(newWidget.widgetList, newWidget)
      }

      this.copyWidget = newWidget
    },

    // 新增专门处理模块内部组件的复制方法
    copyWidgetListForModule(copyWidgetList, parentModule) {
      copyWidgetList.forEach((widget) => {
        widget.id = widget.type.replace(/-/g, '') + generateId()

        let lastId = this.getLastId()
        widget.options.id = lastId
        widget.options.name = `${widget.type}${lastId}`

        if (widget.options.userId) {
          widget.options.userId = this.getLastUserId()
        }

        // 设置父模块ID
        widget.options.parentId = parentModule.id
        widget.options.baseId = parentModule.options.id

        // 递归处理子组件
        if (widget.widgetList) {
          this.copyWidgetListForModule(widget.widgetList, parentModule)
        }
      })
    },

    copyWidgetList(copyWidgetList) {
      copyWidgetList.forEach((widget) => {
        widget.id = widget.type.replace(/-/g, '') + generateId()

        let lastId = this.getLastId()
        widget.options.id = lastId
        widget.options.name = `${widget.type}${lastId}`

        if (widget.options.userId) {
          widget.options.userId = this.getLastUserId()
        }

        if (widget.widgetList) {
          this.copyWidgetList(widget.widgetList)
        }
      })
    },

    // 设计器中黏贴组件
    pasteWidget(position, scale = 1) {
      if (!this.copyWidget) {
        console.warn('No widget to paste - copyWidget is null')
        return
      }

      // 创建新的组件实例以避免引用问题
      const newWidget = deepClone(this.copyWidget)
      const tempId = generateId()
      newWidget.id = newWidget.type.replace(/-/g, '') + tempId

      const lastId = this.getLastId()
      newWidget.options.id = lastId
      newWidget.options.name = `${newWidget.type}${lastId}`

      if (newWidget.options.userId) {
        newWidget.options.userId = this.getLastUserId()
      }

      // 处理子组件
      if (newWidget.widgetList) {
        this.copyWidgetList(newWidget.widgetList)
      }

      // 获取画布信息
      const canvasRect = this.formWidget?.widgetCanvasRef?.getBoundingClientRect()
      const canvasWidth = this.formWidget?.widgetCanvasRef?.offsetWidth || this.size.width
      const canvasHeight = this.formWidget?.widgetCanvasRef?.offsetHeight || this.size.height
      const widgetWidth = newWidget.options.width || 100
      const widgetHeight = newWidget.options.height || 100

      // 设置位置
      if (position && canvasRect) {
        // 计算相对于画布的坐标
        let x = position.x - canvasRect.left
        let y = position.y - canvasRect.top

        // 转换为设计器坐标
        x = Math.round(x / scale)
        y = Math.round(y / scale)

        // 确保组件不会超出画布边界
        x = Math.max(0, Math.min(x, canvasWidth - widgetWidth))
        y = Math.max(0, Math.min(y, canvasHeight - widgetHeight))

        newWidget.options.x = x
        newWidget.options.y = y
      } else {
        // 如果没有位置信息或画布信息，使用默认偏移
        newWidget.options.x += 50
        newWidget.options.y += 50

        // 确保组件不会超出画布边界
        newWidget.options.x = Math.max(0, Math.min(newWidget.options.x, canvasWidth - widgetWidth))
        newWidget.options.y = Math.max(
          0,
          Math.min(newWidget.options.y, canvasHeight - widgetHeight)
        )
      }

      if (this.editedWidget && this.editedWidget.widgetList) {
        this.editedWidget.widgetList.push(newWidget)
      } else {
        this.widgetList.push(newWidget)
      }

      // 复制后自动选中新粘贴的组件
      this.setSelected(newWidget)
      this.copySelectedWidget(newWidget) // 准备下一次粘贴
      this.emitHistoryChange()
    },

    // 删除组件
    deleteWidget(widget, widgetList) {
      let nextSelected = null
      const index = widgetList.findIndex((item) => item.id === widget.id)

      if (index !== -1) {
        if (widgetList.length === 1) {
          nextSelected = null
        } else if (index === widgetList.length - 1) {
          nextSelected = widgetList[index - 1]
        } else {
          nextSelected = widgetList[index + 1]
        }

        widgetList.splice(index, 1)
        this.setSelected(nextSelected)

        this.formWidget.deleteWidgetRef(widget.id) //删除组件ref！！！
        this.emitHistoryChange()
        return
      }

      widgetList.forEach((item) => {
        if (item.widgetList && item.widgetList.length > 0) {
          this.deleteWidget(widget, item.widgetList)
        }
      })
    },

    // 编辑组件
    editWidget(widget) {
      this.copyWidget = null
      this.editedWidget = widget
      if (widget && this.vueInstance?.showEditModal) {
        // 添加检查
        this.vueInstance.showEditModal(widget)
      }
    },

    addFieldByDbClick(widget, parent) {
      let newWidget = this.copyNewFieldWidget(widget, parent)
      if (parent && parent.widgetList) {
        parent.widgetList.push(newWidget)
      } else {
        this.widgetList.push(newWidget)
      }

      this.setSelected(newWidget)
      this.emitHistoryChange()
    },

    emitEvent(evtName, evtData) {
      //用于兄弟组件发射事件
      eventBus.$emit(evtName, evtData)
    },

    handleEvent(evtName, callback) {
      //用于兄弟组件接收事件
      eventBus.$on(evtName, (data) => callback(data))
    },

    setCssClassList(cssClassList) {
      this.cssClassList = cssClassList
    },

    getCssClassList() {
      return this.cssClassList
    },

    registerFormWidget(formWidget) {
      this.formWidget = formWidget
    },

    emitHistoryChange() {
      if (this.historyData.index === this.historyData.maxStep - 1) {
        this.historyData.steps.shift()
      } else {
        this.historyData.index++
      }

      this.historyData.steps[this.historyData.index] = {
        widgetList: deepClone(this.widgetList),
        options: deepClone(this.options)
      }

      if (this.historyData.index < this.historyData.steps.length - 1) {
        this.historyData.steps = this.historyData.steps.slice(0, this.historyData.index + 1)
      }

      // 保存到workspace
      this.saveDesigner()
    },

    saveCurrentHistoryStep() {
      this.historyData.steps[this.historyData.index] = deepClone({
        widgetList: this.widgetList,
        options: this.options
      })

      // 保存到workspace
      this.saveDesigner()
    },

    undoHistoryStep() {
      // console.log('undoHistoryStep', JSON.stringify(this.historyData))
      if (this.historyData.index !== 0) {
        this.historyData.index--
      }

      this.widgetList = deepClone(this.historyData.steps[this.historyData.index].widgetList)
      this.options = deepClone(this.historyData.steps[this.historyData.index].options)

      // 保存到workspace
      this.saveDesigner()
    },

    redoHistoryStep() {
      if (this.historyData.index !== this.historyData.steps.length - 1) {
        this.historyData.index++
      }

      this.widgetList = deepClone(this.historyData.steps[this.historyData.index].widgetList)
      this.options = deepClone(this.historyData.steps[this.historyData.index].options)

      // 保存到workspace
      this.saveDesigner()
    },

    undoEnabled() {
      return this.historyData.index > 0 && this.historyData.steps.length > 0
    },

    redoEnabled() {
      return this.historyData.index < this.historyData.steps.length - 1
    },

    saveDesigner() {
      if (this.vueInstance && typeof this.vueInstance.saveToJson === 'function') {
        try {
          // 确保 vueInstance 有 tabList 属性
          if (!this.vueInstance.tabList) {
            this.vueInstance.tabList = []
          }
          this.vueInstance.saveToJson()
        } catch (error) {
          console.error('Error while saving:', error)
          // 可以选择在这里恢复操作或显示错误信息
        }
      } else {
        console.error('saveToJson is not a function on vueInstance')
      }
    },

    // 设置是否显示组件id
    setShowWidgetId(flag) {
      this.showWidgetId = flag
    },

    // 获取组件ID
    getLastId() {
      return ++this.lastId
    },

    // 获取userId
    getLastUserId() {
      return ++this.lastUserId
    },

    // 判断当前页面是否包含组件
    hasWidget(widget, widgetList = []) {
      return widgetList.find((item) => {
        if (item.id === widget.id) {
          return true
        }
      })
    }
  }
}
